//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package ciicos.point.service.impl;

import ciicos.base.model.filter.RuleInfo;
import ciicos.message.service.MessageService;
import ciicos.model.visiual.superQuery.ConditionJsonModel;
import ciicos.model.visiual.superQuery.SuperQueryConditionModel;
import ciicos.model.visiual.superQuery.SuperQueryJsonModel;
import ciicos.permission.model.authorize.AuthorizeConditionModel;
import ciicos.permission.service.AuthorizeService;
import ciicos.permission.service.UserService;
import ciicos.permission.util.GenUtil;
import ciicos.point.entity.PointSyncEntity;
import ciicos.point.mapper.PointSyncMapper;
import ciicos.point.model.pointsync.PointSyncForm;
import ciicos.point.model.pointsync.PointSyncPagination;
import ciicos.point.result.ScadaNode;
import ciicos.point.service.PointSyncService;
import ciicos.util.GeneraterSwapUtil;
import ciicos.util.JsonUtil;
import ciicos.util.ServletUtil;
import ciicos.util.StringUtil;
import ciicos.util.UserProvider;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PointSyncServiceImpl extends ServiceImpl<PointSyncMapper, PointSyncEntity> implements PointSyncService {
    private static final Logger log = LoggerFactory.getLogger(PointSyncServiceImpl.class);
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private AuthorizeService authorizeService;
    @Autowired
    private UserService userService;
    @Autowired
    private Executor threadPoolExecutor;
    @Autowired
    private MessageService messageService;

    public List<PointSyncEntity> getList(PointSyncPagination pointSyncPagination) {
        return this.getTypeList(pointSyncPagination, pointSyncPagination.getDataType());
    }

    public List<PointSyncEntity> getTypeList(PointSyncPagination pointSyncPagination, String dataType) {
        String userId = this.userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList();
        int total = 0;
        int pointSyncNum = 0;
        QueryWrapper<PointSyncEntity> pointSyncQueryWrapper = new QueryWrapper();
        List<String> allSuperIDlist = new ArrayList();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(pointSyncPagination.getSuperQueryJson())) {
            SuperQueryJsonModel superQueryJsonModel = (SuperQueryJsonModel)JsonUtil.getJsonToBean(pointSyncPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
            String matchLogic = superQueryJsonModel.getMatchLogic();
            List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);

            for(ConditionJsonModel conditionjson : superQueryList) {
                Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
                Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
                String tableName = configMap.get("relationTable") != null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
                if (map.get("multiple") != null && Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
                    conditionjson.setFieldValue("[]");
                }

                conditionjson.setTableName(tableName);
            }

            List<String> allSuperList = new ArrayList();
            List<List<String>> intersectionSuperList = new ArrayList();
            int pointSyncNum1 = 0;
            QueryWrapper<PointSyncEntity> pointSyncSuperWrapper = new QueryWrapper();
            pointSyncNum1 = this.generaterSwapUtil.getCondition(new SuperQueryConditionModel(pointSyncSuperWrapper, superQueryList, matchLogic, "point_sync"), new PointSyncEntity(), pointSyncNum1);
            if (pointSyncNum1 > 0) {
                List<String> pointSyncList = (List)this.list(pointSyncSuperWrapper).stream().map(PointSyncEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(pointSyncList);
                intersectionSuperList.add(pointSyncList);
            }

            superOp = matchLogic;
            if (matchLogic.equalsIgnoreCase("and")) {
                allSuperIDlist = this.generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }

        boolean pcPermission = false;
        boolean appPermission = false;
        boolean isPc = ServletUtil.getHeader("ciicos-origin").equals("pc");
        if (isPc && pcPermission && !this.userProvider.get().getIsAdministrator()) {
            Object pointSyncObj = this.authorizeService.getCondition(new AuthorizeConditionModel(pointSyncQueryWrapper, pointSyncPagination.getMenuId(), "point_sync"));
            if (ObjectUtil.isEmpty(pointSyncObj)) {
                return new ArrayList();
            }

            pointSyncQueryWrapper = (QueryWrapper)pointSyncObj;
            if (pointSyncQueryWrapper.getExpression().getNormal().size() > 0) {
                ++pointSyncNum;
            }
        }

        if (!isPc && appPermission && !this.userProvider.get().getIsAdministrator()) {
            Object pointSyncObj = this.authorizeService.getCondition(new AuthorizeConditionModel(pointSyncQueryWrapper, pointSyncPagination.getMenuId(), "point_sync"));
            if (ObjectUtil.isEmpty(pointSyncObj)) {
                return new ArrayList();
            }

            pointSyncQueryWrapper = (QueryWrapper)pointSyncObj;
            if (pointSyncQueryWrapper.getExpression().getNormal().size() > 0) {
                ++pointSyncNum;
            }
        }

        if (ObjectUtil.isNotEmpty(pointSyncPagination.getNode())) {
            ++pointSyncNum;
            pointSyncQueryWrapper.lambda().like(PointSyncEntity::getNode, pointSyncPagination.getNode());
        }

        if (ObjectUtil.isNotEmpty(pointSyncPagination.getCode())) {
            ++pointSyncNum;
            pointSyncQueryWrapper.lambda().like(PointSyncEntity::getCode, pointSyncPagination.getCode());
        }

        if (ObjectUtil.isNotEmpty(pointSyncPagination.getName())) {
            ++pointSyncNum;
            pointSyncQueryWrapper.lambda().like(PointSyncEntity::getName, pointSyncPagination.getName());
        }

        if (pointSyncPagination.getNodes() != null && pointSyncPagination.getNodes().size() > 0) {
            ++pointSyncNum;
            List<String> nodeList = (List)pointSyncPagination.getNodes().stream().filter(Objects::nonNull).map(ScadaNode::getCode).collect(Collectors.toList());
            pointSyncQueryWrapper.lambda().in(PointSyncEntity::getNode, nodeList);
        }

        if (pointSyncPagination.getType() != null && pointSyncPagination.getType().size() > 0) {
            ++pointSyncNum;
            pointSyncQueryWrapper.lambda().in(PointSyncEntity::getType, pointSyncPagination.getType());
        }

        List<String> intersection = this.generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }

            pointSyncQueryWrapper.lambda().in(PointSyncEntity::getId, intersection);
        }

        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            pointSyncQueryWrapper.lambda().and(t ->
                    t.in(PointSyncEntity::getId, finalAllSuperIDlist)
            );
        }

        if (StringUtil.isEmpty(pointSyncPagination.getSidx())) {
            pointSyncQueryWrapper.lambda().orderByDesc(PointSyncEntity::getId);
        } else {
            try {
                String sidx = pointSyncPagination.getSidx();
                PointSyncEntity pointSyncEntity = new PointSyncEntity();
                Field declaredField = pointSyncEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = ((TableField)declaredField.getAnnotation(TableField.class)).value();
                pointSyncQueryWrapper = "asc".equals(pointSyncPagination.getSort().toLowerCase()) ? (QueryWrapper)pointSyncQueryWrapper.orderByAsc(value) : (QueryWrapper)pointSyncQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        if (!"0".equals(dataType)) {
            return this.list(pointSyncQueryWrapper);
        } else if ((total <= 0 || AllIdList.size() <= 0) && total != 0) {
            List<PointSyncEntity> list = new ArrayList();
            return pointSyncPagination.setData(list, (long)list.size());
        } else {
            Page<PointSyncEntity> page = new Page(pointSyncPagination.getCurrentPage(), pointSyncPagination.getPageSize());
            IPage<PointSyncEntity> userIPage = this.page(page, pointSyncQueryWrapper);
            return pointSyncPagination.setData(userIPage.getRecords(), userIPage.getTotal());
        }
    }

    public QueryWrapper wrapperHandle(QueryWrapper<?> wrapper, String id, Class<?> aClass, String type, String tableName) {
        try {
            wrapper.apply(" 1=1 ", new Object[0]);

            for(RuleInfo info : this.generaterSwapUtil.getFilterCondition(id)) {
                String field = info.getField();
                if ((!"main".equals(type) || !field.contains("-")) && (!"main".equals(type) || !field.contains("_jnpf_")) && (!"sub".equals(type) || field.contains("-")) && (!"sub-ciicos".equals(type) || field.contains("_jnpf_"))) {
                    String fieldName = field;
                    String table = "";
                    if (field.contains("-")) {
                        fieldName = field.split("-")[1];
                    }

                    if (field.contains("_jnpf_")) {
                        fieldName = field.split("_jnpf_")[1];
                        table = field.split("_jnpf_")[0];
                        table = table.replace("jnpf_", "");
                    }

                    if (!"sub-ciicos".equals(type) || tableName.equals(table)) {
                        Field declaredField = aClass.getDeclaredField(fieldName);
                        declaredField.setAccessible(true);
                        String fieldDb = ((TableField)declaredField.getAnnotation(TableField.class)).value();
                        GenUtil genUtil = (GenUtil)JsonUtil.getJsonToBean(info, GenUtil.class);
                        genUtil.solveValue(wrapper, fieldDb);
                    }
                }
            }

            return wrapper;
        } catch (Exception var15) {
            return wrapper;
        }
    }

    public PointSyncEntity getInfo(String id) {
        QueryWrapper<PointSyncEntity> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(PointSyncEntity::getId, id);
        return (PointSyncEntity)this.getOne(queryWrapper);
    }

    public void create(PointSyncEntity entity) {
        this.save(entity);
    }

    public boolean update(String id, PointSyncEntity entity) {
        return this.updateById(entity);
    }

    public void delete(PointSyncEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }

    }

    public String checkForm(PointSyncForm form, int i) {
        int total = 0;
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        String countRecover = "";
        if (isUp) {
            id = form.getId();
        }

        if (ObjectUtil.isNotEmpty(form.getCode())) {
            QueryWrapper<PointSyncEntity> codeWrapper = new QueryWrapper();
            codeWrapper.lambda().eq(PointSyncEntity::getCode, form.getCode());
            if (isUp) {
                codeWrapper.lambda().ne(PointSyncEntity::getId, id);
            }

            if ((int)this.count(codeWrapper) > 0) {
                ++total;
                countRecover = "位号";
            }
        }

        return countRecover;
    }

    public void syncAll() {
        ((PointSyncMapper)this.baseMapper).executePointSyncAll();
    }

    public PointSyncEntity getByCode(String code) {
        QueryWrapper<PointSyncEntity> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(PointSyncEntity::getCode, code);
        return (PointSyncEntity)this.getOne(queryWrapper);
    }

    public List<PointSyncEntity> getListByCode(List<String> codelist) {
        QueryWrapper<PointSyncEntity> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().in(PointSyncEntity::getCode, codelist);
        return this.list(queryWrapper);
    }

    public List<PointSyncEntity> getListByName(List<String> namelist) {
        QueryWrapper<PointSyncEntity> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().in(PointSyncEntity::getName, namelist);
        return this.list(queryWrapper);
    }

    public List<PointSyncEntity> getListByNodeAndName(List<String> nodelist, List<String> namelist) {
        QueryWrapper<PointSyncEntity> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().in(PointSyncEntity::getNode, nodelist);
        queryWrapper.lambda().in(PointSyncEntity::getName, namelist);
        return this.list(queryWrapper);
    }
}
